package leetcode_core.leetcode_3;

import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Set;

class TreeNode {
   int val;
   TreeNode left;
   TreeNode right;
   TreeNode() {}
   TreeNode(int val) { this.val = val; }
   TreeNode(int val, TreeNode left, TreeNode right) {
       this.val = val;
       this.left = left;
       this.right = right;
   }
}

public class MinDepth {
    public int minDepth(TreeNode root) {
        if(root == null){
            return 0;
        }
        int depth = 1;
        Queue<TreeNode> q = new LinkedList<>();
        Set<TreeNode> book = new HashSet<>();
        q.add(root);
        book.add(root);
        while (!q.isEmpty()){
            //这时候将这一层的节点全部拿出来用
            int size = q.size();
            for(int i = 0 ;i<size;i++){
                TreeNode node = q.poll();
                if(node.left == null && node.right == null){
                    return depth;
                }
                //否则话就需要继续入队
                if(node.right!= null){
                    q.add(node.right);
                }
                if(node.left!= null){
                    q.add(node.left);
                }
            }
            depth++;
        }
        return depth;
    }
}
